from flask import Flask, render_template, Response
from flask_cors import CORS
import cv2
import time

app = Flask(__name__)
CORS(app)
camera = None


def init():
    camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    camera.set(6, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    camera.set(cv2.CAP_PROP_FPS, 30)
    return camera


def capture_camera():

    while True:

        ret, frame = camera.read()  # 读取摄像头画面

        if not ret:
            break

        # 在图像上进行处理或其他操作
        # ...

        # 将图像转换为JPG格式
        ret, jpeg = cv2.imencode('.jpg', frame)

        # 将JPEG图像作为HTTP响应发送
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n')

    camera.release()


def provide_image():
    ret, frame = camera.read()  # 读取摄像头画面

    if not ret:
        return


    # 将图像转换为JPG格式
    ret, jpeg = cv2.imencode('.jpg', frame)

        # 将JPEG图像作为HTTP响应发送
    return jpeg.tobytes()


@app.route('/')
@app.route('/index')
def index():
    return '哼哼哼啊啊啊啊'  # 返回HTML模板


@app.route('/video_feed')
def video_feed():
    return Response(capture_camera(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/video')
def video():
    return Response(provide_image(), mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == '__main__':
    camera = init()
    app.run('192.168.124.2', 5005)  # 启动Flask应用程序
